package org.example.zxk.bk.controller;

import com.google.common.net.HttpHeaders;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {


    @GetMapping("/download")
    public ResponseEntity download() throws Exception {
        String filePath = "D:\\libai\\Untitled_0718.sql";
        String fileName = "Untitled_0718.sql";
        fileName = URLEncoder.encode(fileName,"UTF-8");
        File file = new File(filePath);
        if(!file.exists()){
            throw new Exception("文件不存在");
        }
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=" + fileName ).body(new FileSystemResource(filePath));
    }
    @GetMapping("/download1")
    public void ioDownload(HttpServletResponse response) throws Exception {
        String filePath = "D:\\libai\\Untitled_0718.sql";
        String fileName = "Untitled_0718.sql";
        fileName = URLEncoder.encode(fileName,"UTF-8");
        File file=new File(filePath);
        if(!file.exists()){
            throw new Exception("文件不存在");
        }
        response.setHeader("Content-disposition","attachment;filename="+ fileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        IOUtils.copy(fileInputStream,response.getOutputStream());
        response.flushBuffer();
        fileInputStream.close();
    }
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        String storagePath = "D:\\";
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空！");
        }
        String originalFilename = file.getOriginalFilename();
        String newFileName = UUID.randomUUID()+"_"+originalFilename;
        String filePath = storagePath+newFileName;
        File file1 = new File(filePath);
        if (!file1.getParentFile().exists()) {
            file1.getParentFile().mkdirs();
        }
        file.transferTo(file1);
        return filePath;
    }
}
